package com.cinco.server.controller;

import com.cinco.server.pojo.Admin;
import com.cinco.server.pojo.Result;
import com.cinco.server.service.IAdminService;
import com.cinco.server.utils.FastDFSUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author cinco
 * @version 1.0
 * @date 2022/1/21
 */
@RestController
public class AdminInfoController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "更新用户信息")
    @PutMapping("/admin/info")
    public Result updateAdminInfo(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return Result.success("更新成功!");
        }
        return Result.error("更新失败！");
    }

    @ApiOperation(value = "修改密码")
    @PutMapping("/admin/pass")
    public Result updateAdminPassword(@RequestBody Map<String,Object> info){
        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassword(oldPass,pass,adminId);
    }

    @ApiOperation(value = "修改头像")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "头像", dataType = "MultipartFile")})
    @PostMapping("/admin/userface")
    public Result updateAdminUserface(MultipartFile file, Integer id, Authentication authentication) {
        String[] fileAbsolutePath = FastDFSUtils.upload(file);
        /**
         * FastDFSUtils.getTrackerUrl() :  ip+port
         * fileAbsolutePath[0] :  group_name
         * fileAbsolutePath[1] :  file_name
         */
        String url = FastDFSUtils.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
        return adminService.updateAdminUserface(url, id, authentication);
    }
}
